# coding: utf-8
from typing import List

from PySide6.QtWidgets import QTableWidgetItem

from common import sqlRequest, signalBus
from components import ViewTableWidget
from server.db import history_view_list, HistoryViewTabelModel, clear_history_view, delete_history_view


class ViewInterface(ViewTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.tableData = {}

        self.__initWidgets()

    def __initWidgets(self):
        headers = ['名称', '描述', '源地址', '查看时间', 'ID']
        self.setHorizontalHeaderLabels(headers)

        self.clearSignal.connect(lambda: sqlRequest(clear_history_view))

    def updateTable(self, models: List[HistoryViewTabelModel]):
        self.setRowCount(len(models))
        for i, model in enumerate(models):
            self.addItem(model.title, i, 0)
            self.addItem(model.description, i, 1)
            self.addItem(model.url, i, 2)
            time = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
            self.addItem(time, i, 3)
            self.addItem(str(model.id), i, 4)

            self.setRowHeight(i, 50)
        self.setColumnHidden(4, True)

    def removeSelectedRows(self):
        rows = self.selectionModel().selectedRows()[::-1]
        if not rows:
            return
        for row in rows:
            index = row.row()
            self.removeRow(index)

            print(index, self.itemFromIndex(row))
            # sqlRequest(delete_history_view, _id)

    def reload(self):
        self.clearTable()
        sqlRequest(history_view_list, slot=self.updateTable)

    def onItemDoubleClicked(self, item: QTableWidgetItem):
        row = item.row()
        title = self.item(row, 0).text()
        description = self.item(row, 1).text()
        url = self.item(row, 2).text()
        signalBus.showImageSignal.emit(title, description, url)
